package com.hao1st.service2.biz.distributedtx.service.impl;

import com.hao1st.service2.biz.distributedtx.service.DTXService;
import com.hao1st.service2.dbmap.entities.TUser;
import com.hao1st.service2.dbmap.imapper.TUserMapper;
import com.hao1st.service2.rpc.Service1Rpc;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class DTXServiceImpl implements DTXService {

    @Resource
    private TUserMapper tUserMapper;

    @Resource
    private CircuitBreakerFactory cbFactory;

    @Resource
    private Service1Rpc service1Rpc;

//    @GlobalTransactional(name = "demo-global-tx", rollbackFor = Exception.class)
    @Override
    public String insNewUser(HttpHeaders httpHeaders) throws Exception {

        TUser tuser = new TUser();
        tuser.setUserId("0002");
        tuser.setUserName("DistributedTXUser");

        String retStr = "创建用户失败";
        // service2数据库插入数据
        if (tUserMapper.insert(tuser) != 0) {
            if (true) {
                log.warn("#手动抛出一个异常");
                throw new Exception("手动抛出一个异常");
            }
            // rpc调用service1插入数据
            retStr = cbFactory.create("invoke").run(() -> service1Rpc.invokeService1UserIndex(httpHeaders), throwable -> throwable.getMessage());
        }

        return retStr;

    }
}
